package tpase.StorageServer.Service.Impl;

import tpase.StorageServer.DAO.FileInfoDao;
import tpase.StorageServer.DAO.UserAuthDao;
import tpase.StorageServer.DO.FileInfo;
import tpase.StorageServer.DO.UserAuth;
import tpase.StorageServer.Service.StorageServerService;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class StorageServerServiceImpl implements StorageServerService {
    private UserAuthDao userAuthDao;
    private FileInfoDao fileInfoDao;

    public StorageServerServiceImpl() {
        String configPath = "config/config.properties";
        userAuthDao = new UserAuthDao(configPath);
        fileInfoDao = new FileInfoDao(configPath);
    }

    @Override
    public boolean hasUid(String uid) {
        UserAuth userAuth = userAuthDao.getUserAuth(uid);
        return userAuth != null;
    }

    @Override
    public void storeAuth(UserAuth userAuth) {
        userAuthDao.storeUserAuth(userAuth);
    }

    @Override
    public byte[] getUserAuth(String uid) {
        return userAuthDao.getUserAuth(uid).getAuth();
    }

    @Override
    public void clear() {
        userAuthDao.clearUserAuth();
    }

    @Override
    public List<FileInfo> getFileInfoList(String uid) {
        return fileInfoDao.getFileInfoList(uid);
    }

    @Override
    public void deleteFile(String fid) {
        FileInfo fileInfo = fileInfoDao.getFileInfo(fid);
        Path path = Paths.get(fileInfo.getPath());
        try {
            Files.delete(path);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        fileInfoDao.deleteFileInfo(fid);
    }

    @Override
    public void storeFile(FileInfo fileInfo) {
        fileInfoDao.storeFileInfo(fileInfo);
    }

    @Override
    public FileInfo getFileInfo(String fid) {
        return fileInfoDao.getFileInfo(fid);
    }
}
